<template>
	<view class="father">
		<view class="gridNoMb text-center" :class="gClass" id="tabber">
			<view :style="{color: index == curIndex ? activeColor : '#333'}" v-for="( item , index) in list" :key="index" @tap="tapItem(index)">
				{{ !!itemKey ? item[itemKey] : item}}
			</view>
		</view>
		<view v-if="width > 0" class="abs bottom bottomer" :style="{left : left + 'px','background-color' : activeColor}"></view>
	</view>
</template>

<script>
	export default {
		name : 'switchTabber' ,
		props:{
			list : {
				type : Array ,
				default : function(e){
					return [] ;
				}
			},
			index : {
				default : 0
			},
			itemKey : {
				default : ""
			},
			activeColor:{
				default : "#3385ff"
			}
		},
		
		data() {
			return {
				curIndex : 0 ,
				width : 0
			};
		},
		
		mounted() {
			this.$nextTick(()=>{
				this.computeHeight();
			})
		},
		
		watch:{
			index : function(index){
				this.curIndex = index ;
			},
		},
		
		computed:{
			left : function(){
				var perWidth = this.width * 1/this.list.length ;
				return 5 + perWidth * this.curIndex + perWidth/2 - 10 ; 
			},
			gClass:function(){
				return 'g' + this.list.length + ' ' + (this.width > 0 ? '' : 'op0') ;
			},
		},
		
		methods:{
			
			computeHeight:function(e){
				const query = uni.createSelectorQuery().in(this);
				query.select('#tabber').boundingClientRect(data => {
					var width = data.width  ;
					if (width > 0) {
						this.width = data.width - 10;
					}
				}).exec();
			},
			
			tapItem : function(index){
				if(this.curIndex == index){
					return ;
				}
				this.$emit("change" , {index : index});
			}
		},
		
	}
</script>

<style lang="scss" scoped>
	.bottomer{
		background-color: $main;
		width: 40upx;
		-webkit-border-radius: 23px;
		-moz-border-radius: 23px;
		border-radius: 23px;
		height: 3px;
		display: block;
		transition: all 0.4s ;
	}
</style>
